package eerbaar.persona;

import eerbaar.body.BodyFactory;
import eerbaar.body.IHead;
import eerbaar.internal.elements.Element;
import eerbaar.message.lib.StateChangeMsg;
import eerbaar.position.IPosition;
import eerbaar.position.IPositionListener;
import eerbaar.position.WrongPositionException;
import eerbaar.shared.message.MsgHelper;

public class Persona extends Element implements IPersona {

    private Direction direction = IPersona.Direction.LEFT;
    private IHead head;
    private String program;
    private State state = IPersona.State.REST;

    public Persona(String name, int x, int y) {
        super(name, x, y);
        this.head = BodyFactory.createHead();
        registerListener();
    }

    public Persona(String name, int x, int y, String program) {
        super(name, x, y);
        this.program = program;
        this.head = BodyFactory.createHead();
        registerListener();
    }

    public Persona(String name, IPosition position, IHead head) {
        super(name, position);
        this.head = head;
        registerListener();
    }

    @Override
    public IPersona copy() {
        return new Persona(this.getName(), this.getPosition().getX(), this
                .getPosition().getY(), this.program);
    }

    @Override
    public IPersona.Direction getDirection() {
        return this.direction;
    }

    @Override
    public IHead getHead() {
        return this.head;
    }

    @Override
    public String getProgram() {
        return this.program;
    }

    @Override
    public IPersona.State getState() {
        return this.state;
    }

    @Override
    public int hashCode() {
        return toString().hashCode();
    }

    private void registerListener() {

        IPositionListener listener = new IPositionListener() {

            @Override
            public void afterPositionChange(IPosition oldPos, IPosition pos) {

                if (pos.getX() > oldPos.getX()) {
                    Persona.this.direction = IPersona.Direction.RIGHT;
                } else {
                    Persona.this.direction = IPersona.Direction.LEFT;
                }
            }

            @Override
            public void beforePositionChange(IPosition pos)
                    throws WrongPositionException {
                //
            }
        };

        super.getPosition().addListener(listener);
    }

    @Override
    public void setHead(IHead head) {
        this.head = head;
    }

    @Override
    public void setPosition(final IPosition inPosition) {
        super.setPosition(inPosition);
        registerListener();
    }

    @Override
    public void setProgram(String program) {
        this.program = program;
    }

    @Override
    public void setState(IPersona.State state) {
        if (this.state == null || !this.state.equals(state)) {
            MsgHelper.sendToDefaultReaders(new StateChangeMsg());
        }
        this.state = state;
    }

}
